package com.czh.codesandbox;

import cn.hutool.core.date.StopWatch;

import cn.hutool.core.util.ArrayUtil;
import com.czh.codesandbox.model.ExecMessage;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import org.springframework.stereotype.Component;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/*
 * ClassName: JavaDockerCodeSandbox
 * Package: com.czh.codesandbox
 * Description:
 *            Docker代码沙箱
 * @Author: CZH
 * @Create: 2025
 */
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate {

    //执行超时时间
    private static final long TIME_OUT = 5000L;

    private static final Boolean FIRST_DONE_IMAGE = true;

    /**
     * 继承JavaCodeSandboxTemplate模板，重写运行实现
     * @param codeFile
     * @param inputList
     * @return
     */
    @Override
    public List<ExecMessage> runFile(File codeFile, List<String> inputList) {
        String userCodeFilePath = codeFile.getParentFile().getAbsolutePath();
        //3、拉取镜像，创建容器，将.class文件复制到容器中
        //创建连接
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
//        PingCmd pingCmd = dockerClient.pingCmd();
//        pingCmd.exec();

        //拉取镜像
        String img = "openjdk:8-alpine";
//        String img = "hello-world";
        if (FIRST_DONE_IMAGE) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(img);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {

                @Override
                public void onNext(PullResponseItem item) {
                    System.out.println("下载镜像中：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd
                        .exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                System.out.println("镜像拉取异常！！！");
                throw new RuntimeException(e);
            }
            System.out.println("下载完成！");
        }

        //创建容器
        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(img);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);//设置内存
        hostConfig.withMemorySwap(0L);
        hostConfig.withCpuCount(1L);//设置cpu内核数
        hostConfig.setBinds(new Bind(userCodeFilePath, new Volume("/app")));//将本地目录同步到容器中，使容器能够访问
        CreateContainerResponse createContainerResponse = createContainerCmd
                .withHostConfig(hostConfig)
                .withReadonlyRootfs(true)//设置用户禁止向root根目录写文件
                .withNetworkDisabled(true)//设置容器禁止联网
                .withAttachStdin(true)//开启docker和本地控制台连接，来获取输入
                .withAttachStderr(true)//开启docker和本地控制台连接，来获取错误信息
                .withAttachStdout(true)//开启docker和本地控制台连接，来获取输出
                .withTty(true)//开启docker和本地的交互控制台,会在后台持续存在接收输入
                .exec();
        System.out.println(createContainerResponse);

        //启动容器
        String containerId = createContainerResponse.getId();
        dockerClient.startContainerCmd(containerId).exec();

        //执行java命令，运行.class文件,获取执行结果
        //docker exec infallible_goldberg java -cp /app Main 1 5
        List<ExecMessage> execMessagesList = new ArrayList<>();
        for (String inputArgs : inputList) {
            //创建计时器，计算运行时间
            StopWatch stopWatch = new StopWatch();
            //通过空格，分割输入用例
            String[] oneArgs = inputArgs.split(" ");
            //将输入用例，拼接到docker exec infallible_goldberg java -cp /app Main 后
            String[] javaCmd = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, oneArgs);
            //创建执行命令
            ExecCreateCmdResponse createCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(javaCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            System.out.println("执行命令：" + createCmdResponse);
            ExecMessage executeMessage = new ExecMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};
            //获取容器Id
            String id = createCmdResponse.getId();
            //初始化运行时间
            long runingTime = 0l;
            //超时判断，默认true
            final boolean[] timeout = {true};
            //创建执行回调
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onComplete() {
                    //如果在超时时间内执行完成，会执行此方法，同时超时判断会修改为false
                    timeout[0] = false;
                    super.onComplete();
                }

                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                        System.out.println("输出错误结果：" + errorMessage[0]);

                    } else {
                        message[0] = new String(frame.getPayload());
                        System.out.println("输出结果：" + message[0]);
                    }
                    super.onNext(frame);
                }
            };
            //初始化最大运行内存
            final long[] maxMemory = {0L};
            //创建docker自带的状态查看命令
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            //执行命令
            ResultCallback<Statistics> exec = statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {
                }

                @Override
                public void onNext(Statistics statistics) {
                    System.out.println(statistics.getMemoryStats().getUsage());
                    //获取最大运行内存
                    maxMemory[0] = Math.max(statistics.getMemoryStats().getUsage(), maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {
                }

                @Override
                public void onComplete() {
                }

                @Override
                public void close() throws IOException {
                }
            });
            statsCmd.exec(exec);
            try {
                //开始记时
                stopWatch.start();
                //开始运行代码
                dockerClient.execStartCmd(id)
                        .exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MICROSECONDS);//设置超时时间，如果在超时时间内执行完成，会执行execStartResultCallback回调的（onComplete）方法，
                //结束记时
                stopWatch.stop();
                //记录运行时间
                runingTime = stopWatch.getLastTaskTimeMillis();
                statsCmd.close();
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrormessage(errorMessage[0]);
            executeMessage.setTime(runingTime);
            executeMessage.setMemory(maxMemory[0]);
            execMessagesList.add(executeMessage);

        }
        return  execMessagesList;
    }


}
